package com.mars.common.util;

import com.mars.common.constant.Constant;
import com.mars.common.enums.FieldTypeEnums;
import com.mars.framework.handler.TransHandler;
import com.mars.module.tool.request.FieldRequest;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2023-11-14 18:27:28
 */
public class SqlGeneratorUtils {


    /**
     * 生成表结构
     *
     * @param fieldInfoList  字段信息
     * @param tableName      表名称
     * @param isGenBaseField 是否生成基础字段
     * @param name           中文名称
     * @return String
     */
    public static String generateDynamicSQL(List<FieldRequest> fieldInfoList, String tableName, boolean isGenBaseField, String name) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("CREATE TABLE ").append("`").append(tableName).append("`").append(" (\n");
        fieldInfoList.sort(Comparator.comparingInt(FieldRequest::getSort));
        sqlBuilder.append("`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',\n");
        for (FieldRequest fieldInfo : fieldInfoList) {

            String fieldName = fieldInfo.getFieldName();
            String fieldType = convertFieldType(fieldInfo.getFieldType());
            if (fieldName.equals(Constant.SORT)) {
                break;
            }
            Integer fieldLength = fieldInfo.getFieldLength();
            String fieldComment = fieldInfo.getFieldComment();
            boolean defaultNull = fieldInfo.isDefaultNull();
            String defaultValue = fieldInfo.getDefaultValue();

            // 添加字段定义
            sqlBuilder.append("`").append(fieldName).append("`").append(" ").append(fieldType);
            if (fieldLength != null) {
                if (fieldType.equalsIgnoreCase(FieldTypeEnums.VARCHAR.getDbType()) || fieldType.equalsIgnoreCase(FieldTypeEnums.TEXTAREA.getDbType())) {
                    sqlBuilder.append("(").append(fieldLength).append(") CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci");
                } else if (fieldType.equalsIgnoreCase(FieldTypeEnums.BIGDECIMAL.getDbType())) {
                    sqlBuilder.append("(10,").append(fieldLength).append(")");
                }
            }
            if (StringUtil.isNotEmpty(defaultValue)) {
                sqlBuilder.append(" DEFAULT ").append("'").append(defaultValue).append("'");
            } else {
                if (defaultNull) {
                    sqlBuilder.append(" DEFAULT NULL");
                } else {
                    sqlBuilder.append(" NOT NULL");
                }
            }

            // 添加字段注释
            if (fieldComment != null) {
                sqlBuilder.append(" COMMENT '").append(fieldComment).append("',\n");
            }
        }
        appendBaseField(isGenBaseField, sqlBuilder);
        sqlBuilder.append("PRIMARY KEY (`id`) USING BTREE \n)");
        // 移除最后一个逗号
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='").append(name).append("';");
        return sqlBuilder.toString();
    }

    private static String convertFieldType(String fieldType) {
        return FieldTypeEnums.getDbTypeByType(fieldType);
    }


    /**
     * 基础字段
     *
     * @param isGenBaseField isGenBaseField
     * @param sqlBuilder     sqlBuilder
     */
    private static void appendBaseField(boolean isGenBaseField, StringBuilder sqlBuilder) {
        if (isGenBaseField) {
            sqlBuilder.append("`create_by_id` bigint DEFAULT NULL COMMENT '创建人账号',\n");
            sqlBuilder.append("`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n");
            sqlBuilder.append("`create_by_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '创建人名称',\n");
            sqlBuilder.append("`update_by_id` bigint DEFAULT NULL COMMENT '更新人账号',\n");
            sqlBuilder.append("`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',\n");
            sqlBuilder.append("`update_by_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '更新人名称',\n");
            sqlBuilder.append("`deleted` tinyint(1) DEFAULT '0' COMMENT '逻辑删除',\n");
        }
    }

    public static void main(String[] args) {
        ArrayList<FieldRequest> list = new ArrayList<>();
        FieldRequest request = new FieldRequest();
        request.setFieldName("名称");
        request.setFieldType("STRING");
        request.setFieldLength(100);
        request.setSort(1);
        request.setDefaultNull(false);
        list.add(request);


        FieldRequest request1 = new FieldRequest();
        request1.setFieldName("图片1");
        request1.setFieldType("BIGDECIMAL");
        request1.setFieldLength(2);
        request1.setSort(2);
        request1.setDefaultValue("1");
        request1.setDefaultNull(false);
        list.add(request1);

        FieldRequest request2 = new FieldRequest();
        request2.setFieldName("支付时间");
        request2.setFieldType("LOCALDATETIME");
        request2.setFieldLength(2);
        request2.setSort(3);
        list.add(request2);


        List<FieldRequest> fieldRequestList = list.stream().peek(s -> {
            s.setFieldComment(s.getFieldName());
            String fieldName = s.getFieldName();
            String enFieldName = TransHandler.trans(fieldName);
            s.setFieldName(enFieldName);
        }).collect(Collectors.toList());
        String s = generateDynamicSQL(fieldRequestList, "user", true, "用户表");
        System.out.println(s);
    }

}
